import json
import Config as C
import MySQL


def normalize_result():
    results = MySQL.query('SELECT * FROM tpch_result')
    for row in results:
        normalized = row['normalized']
        if normalized == 0:
            row['normalized'] = 1
            size = row['size']
            result = row['result']
            objs = json.loads(result)
            for obj in objs:
                for key in obj.keys():
                    if key.find('sum') >= 0:
                        obj[key] = obj[key] * C.DEFAULT_NORMALIZATION_SIZE / size
                    elif key.find('count') >= 0:
                        obj[key] = obj[key] * C.DEFAULT_NORMALIZATION_SIZE / size
                    elif key.find('revenue') >= 0:
                        obj[key] = obj[key] * C.DEFAULT_NORMALIZATION_SIZE / size
            MySQL.update('tpch_result', {
                'normalized': 1,
                'result': json.dumps(objs)
            }, 'id=' + str(row['id']))


def normalize_distribution(dist_id):
    sql = 'SELECT * FROM `tpch_distribution` WHERE `id`=' + str(dist_id)
    dist = MySQL.query(sql)[0]
    for i in range(C.DEFAULT_DATA_START, C.DEFAULT_DATA_END + C.DEFAULT_DATA_DELTA - 1, C.DEFAULT_DATA_DELTA):
        dist_table = dist['table'] + '_' + str(i) + 'w' + '_dist_' + dist['column_label'] + '_' + str(dist['unit_size']) + '_' + str(dist['id'])
        count_label = dist['count_label']
        group_label = dist['group_label']
        sql = 'SELECT SUM({count_label}) AS sum_count FROM {dist_table}'.format(count_label=count_label, dist_table=dist_table)
        sum_count = MySQL.query(sql)[0]['sum_count']
        sql = 'SELECT * FROM ' + dist_table
        results = MySQL.query(sql)
        for row in results:
            if row['normalized'] == 0:
                result = row[count_label]
                result = result / sum_count
                MySQL.update(dist_table, {
                    'normalized': 1,
                    count_label: result
                }, group_label + '=' + str(row[group_label]))


if __name__ == '__main__':
    # normalize_result()
    normalize_distribution(5)
